package com.ruoyi.common.utils.cloudroom;

import okhttp3.*;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 表单上传文件调用
     * @param url
     * @param param
     * @param file
     * @return
     * @throws Exception
     */
    public static String formToStr(String url, Map<String, Object> param, File file) throws Exception{
        if (file == null || !file.exists()){
            System.out.println("文件不存在");
            return null;
        }
        // 添加请求参数
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (param != null && param.size() > 0) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                if (entry.getValue() != null){
                    builder.addFormDataPart(entry.getKey(), entry.getValue().toString());
                }
            }
        }

        // 上传文件
        RequestBody requestBody = builder
                .addFormDataPart("file", file.getName(), RequestBody.create(MultipartBody.FORM, file)).build();
        return post(url, requestBody).body().string();
    }

    public static String postToStr(String url, String requestJson) throws Exception{
        System.out.println("requestJson: " + requestJson);
        RequestBody requestBody = RequestBody.create(JSON, requestJson);
        return post(url, requestBody).body().string();
    }

    /**
     * 同步post调用
     * @param url
     * @param requestBody
     * @return
     * @throws Exception
     */
    public static Response post(String url, RequestBody requestBody) throws Exception{
        Response response = getCall(url, requestBody, -1L).execute();
        if (!response.isSuccessful()){
            System.out.println("url: " + url + ", 调用失败, response: " + response);
        }
        return response;
    }

    public static void asyncPost(String url, String requestJson, Callback callback) throws Exception{
        asyncPost(url, requestJson, callback, -1L);
    }

    /**
     * 异步调用
     * @param url
     * @param requestJson
     * @param callback  异步结果回调事件
     * @throws Exception
     */
    public static void asyncPost(String url, String requestJson, Callback callback, long timeOut) throws Exception{
        RequestBody requestBody = RequestBody.create(JSON, requestJson);
        getCall(url, requestBody, timeOut).enqueue(callback);
    }

    public static Call getCall(String url, RequestBody requestBody, long timeOut) throws Exception{
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return getClient(timeOut).newCall(request);
    }

    /**
     *
     * @param timeOut 超时时长，单位：秒，负数则使用默认值
     * @return
     * @throws Exception
     */
    public static OkHttpClient getClient(long timeOut) throws Exception{
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (timeOut > 0){
            builder
                    .connectTimeout(timeOut, TimeUnit.SECONDS)
                    .readTimeout(timeOut, TimeUnit.SECONDS)
                    .writeTimeout(timeOut, TimeUnit.SECONDS);
        }
        return builder.build();
    }
}
